<script setup lang="ts">
import { computed } from "vue";
import dayjs, { Dayjs } from "dayjs";
import { watch } from "vue";

type TProps = {
  valueFormat?: "YYYY-MM-DD HH:mm:ss" | "YYYY-MM-DD" | "x" | "s";
  placeholders?: string[];
};

const props = defineProps<TProps>();

const start = defineModel<string | number | Date>("start");
const end = defineModel<string | number | Date>("end");

watch(start, (val) => {
  // 其实就是置空
  if (!start) end.value = val;
});

const emits = defineEmits<{
  (e: "update:start", v: any): void;
  (e: "update:end", v: any): void;
  (e: "update:modelValue", v: [any, any]): void;
}>();

const isSecondFormat = computed(() => props.valueFormat == "s");

const date = computed({
  get() {
    return [start.value, end.value].map((e: any) =>
      isSecondFormat.value ? toValue(e) : e
    );
  },
  set(value) {
    let sV, eV;

    if (value) {
      let [s, e] = value;
      e = handleEndDate(e);
      const flag = isSecondFormat.value;
      sV = flag ? toUnix(s) : s;
      eV = flag ? toUnix(e) : e;
    }

    start.value = sV;
    end.value = eV;

    emits("update:start", sV);
    emits("update:end", eV);
    emits("update:modelValue", [sV, eV]);
  },
});

// 设置结束时间为 23:59:59
function handleEndDate(date: string | Date | Dayjs) {
  date = dayjs(date).endOf("day");
  switch (props.valueFormat) {
    case "x":
    case "s":
      return date.valueOf();
    case "YYYY-MM-DD":
      return date.format(props.valueFormat);
    case "YYYY-MM-DD HH:mm:ss":
      return date.format(props.valueFormat);
    default:
      return date.toDate();
  }
}

// 时间戳（秒）
function toUnix(val: number) {
  return Math.floor(val / 1000);
}

// 时间戳（毫秒）
function toValue(val: number) {
  return val * 1000;
}
</script>

<template>
  <el-date-picker
    v-model="date"
    type="daterange"
    :start-placeholder="placeholders?.[0] || '开始时间'"
    :end-placeholder="placeholders?.[1] || '结束时间'"
    :value-format="isSecondFormat ? 'x' : valueFormat"
  />
</template>
